package com.cjx.api.service.impl;

import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cjx.api.annotation.AuthCheck;
import com.cjx.api.common.ErrorCode;
import com.cjx.api.exception.BusinessException;
import com.cjx.api.mapper.InterfaceInfoMapper;
import com.cjx.api.model.dto.interfaceinfo.InvokeRequest;
import com.cjx.api.model.dto.userinterfaceinvoke.UserInterfaceInvokeAddRequest;
import com.cjx.api.model.entity.InterfaceInfo;
import com.cjx.api.model.entity.User;
import com.cjx.api.model.entity.UserInterfaceInvoke;
import com.cjx.api.model.vo.UserVO;
import com.cjx.api.service.InterfaceInfoService;
import com.cjx.api.service.UserInterfaceInvokeService;
import com.cjx.api.service.UserService;
import com.cjx.starsapisdk.client.StarsApiClient;
import com.cjx.starsapisdk.model.response.ResultResponse;
import org.springframework.data.redis.connection.ReactiveNumberCommands;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.cjx.api.constant.UserConstant.ADMIN_ROLE;
import static com.cjx.api.constant.UserConstant.USER_LOGIN_STATE;
import static com.cjx.api.model.enums.InterfaceStatusEnum.INTERFACE_OFFLINE;
import static com.cjx.api.model.enums.InterfaceStatusEnum.INTERFACE_ONLINE;

/**
* @author cjx
* @description 针对表【interface_info(用户接口调用信息)】的数据库操作Service实现
* @createDate 2024-05-04 21:55:48
*/
@Service
public class InterfaceInfoServiceImpl extends ServiceImpl<InterfaceInfoMapper, InterfaceInfo>
    implements InterfaceInfoService {

    @Resource
    private StarsApiClient starsApiClient;
    @Resource
    private UserInterfaceInvokeService userInterfaceInvokeService;
    @Resource
    private UserService userService;

    @Override
    @AuthCheck(mustRole = ADMIN_ROLE)
    public Boolean offlineInterface(long id, HttpServletRequest request) {
        //判断用户接口调用是否操作
        InterfaceInfo interfaceInfo = getById(id);
        if (interfaceInfo == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //TODO:判断用户接口调用是否可以调用
        //判断用户接口调用状态是否已是下线状态
        if (interfaceInfo.getStatus() == INTERFACE_OFFLINE.getValue()){
            return true;
        }
        LambdaUpdateWrapper<InterfaceInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(InterfaceInfo::getId,id);
        updateWrapper.set(InterfaceInfo::getStatus,INTERFACE_OFFLINE.getValue());
        boolean res = update(updateWrapper);
        if (BooleanUtil.isFalse(res)){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        return res;
    }

    @Override
    @AuthCheck(mustRole = ADMIN_ROLE)
    public boolean onlineInterface(long id, HttpServletRequest request) {
        //判断用户接口调用是否操作
        InterfaceInfo interfaceInfo = getById(id);
        if (interfaceInfo == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //判断用户接口调用状态是否已是上线状态
        if (interfaceInfo.getStatus() == INTERFACE_ONLINE.getValue()){
            return true;
        }
        LambdaUpdateWrapper<InterfaceInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(InterfaceInfo::getId,id);
        updateWrapper.set(InterfaceInfo::getStatus,INTERFACE_ONLINE.getValue());
        boolean res = update(updateWrapper);
        if (BooleanUtil.isFalse(res)){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        return res;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultResponse invokeInterface(InvokeRequest invokeRequest, HttpServletRequest request) {
        Long id = invokeRequest.getId();

        // 1. 根据用户接口调用id获取用户接口调用信息
        InterfaceInfo interfaceInfo = getById(id);
        if (interfaceInfo == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        Long reduceScore = interfaceInfo.getReduceScore();
        // 2. 比对请求参数是否合理
        // 3. 判断用户接口调用是否可用
        // 4. 检查用户余额是否够用
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (user == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        if (user.getBalance() < reduceScore){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"余额不足");
        }
        // 5. 利用用户接口调用地址和参数调用对应的用户接口调用方法
        String url = interfaceInfo.getUrl();
        List<InvokeRequest.Field> requestParams = invokeRequest.getRequestParams();
        InvokeRequest.Field field = requestParams.get(0);
        Map<String,Object> params = new HashMap<>();
        params.put(field.getFieldName(),field.getValue());
        ResultResponse res = starsApiClient.sentGetNameHttp(field.getValue());
        System.out.println("res = " + res);
        /*// 6. 调用次数和余额扣减
        LambdaUpdateWrapper<InterfaceInfo> infoLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        infoLambdaUpdateWrapper.eq(InterfaceInfo::getId,id);
        infoLambdaUpdateWrapper.setSql("totalInvokes =  totalInvokes + 1");
        if (!update(infoLambdaUpdateWrapper)) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        // 6.1 判断是否存在此条调用关系
        UserInterfaceInvoke invokeRecording = userInterfaceInvokeService.getOne(
                new LambdaQueryWrapper<UserInterfaceInvoke>()
                        .eq(UserInterfaceInvoke::getUserId, user.getId())
                        .eq(UserInterfaceInvoke::getInterfaceId, id)
        );
        if (invokeRecording != null){
            //6.2 存在则修改
            boolean onceRes = userInterfaceInvokeService.invokeResultInUpdate(invokeRecording.getId());
            if (!onceRes){
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        }else{
            //6.3 不存在则创建调用记录
            UserInterfaceInvokeAddRequest newInvokeRecording = new UserInterfaceInvokeAddRequest();
            newInvokeRecording.setUserId(user.getId());
            newInvokeRecording.setInterfaceId(id);
            newInvokeRecording.setTotalInvokes(1L);
            boolean onceRes = userInterfaceInvokeService.addUserInterfaceInvoke(newInvokeRecording);
            if (!onceRes){
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        }
        //6.4 扣减用户余额
        if (!userService.updateUserBalance(user.getId(),interfaceInfo.getReduceScore())) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }*/
        return res;
    }
}




